package com.zt.rongda.group.service;

import java.util.List;

import com.zt.rongda.constant.BusConstant;
import com.zt.rongda.group.inter.EmployeeGroupMapper;
import com.zt.rongda.group.inter.EmployeeGroupMemberMapper;
import com.zt.rongda.group.model.EmployeeGroup;
import com.zt.rongda.group.model.EmployeeGroupMember;
import com.zt.servlet.FieldAlias;
import com.zt.system.model.BusinessException;
import com.zt.servlet.ReqBean;
import com.zt.system.model.SqlBuilder;
import com.zt.system.service.BaseService;
import com.zt.system.service.IFieldAliasService;
import com.zt.util.StringUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

@Service
public class EmployeeGroupService extends BaseService implements IFieldAliasService {

    @Autowired
    private EmployeeGroupMapper employeeGroupMapper;

    @Autowired
    private EmployeeGroupMemberMapper groupMemberMapper;

    /**
     * 查询
     * 
     * @param reqBean
     * @return
     */
    @FieldAlias(service = "employeeGroupService", field = "groupId", alias = "groupDetails")
    public JSONObject getTable(ReqBean reqBean) {
        SqlBuilder sqlBuilder = new SqlBuilder("");
        sqlBuilder.appendSql("select * from EMPLOYEE_GROUP a where 1=1 ")
                .addWhereLike2("a.GROUP_NAME", reqBean.getInfo("groupName"))
                .addWhere("a.GROUP_TYPE", reqBean.getInfo("groupType"))
                .addWhere("a.STATUS", BusConstant.EmployeeGroup.STATUS_ENABLE);
        return queryTable(sqlBuilder, reqBean.getPageSize(), reqBean.getPageIndex());
    }

    /**
     * 通过id查询
     * 
     * @param groupId
     * @return
     */
    public EmployeeGroup getById(String groupId) {
        return employeeGroupMapper.selectByPrimaryKey(groupId);
    }

    /**
     * 新增
     * 
     * @param employeeGroup
     */
    public void add(EmployeeGroup employeeGroup) {
        employeeGroup.setGroupId(intIncrementId("EMPLOYEE_GROUP", "GROUP_ID"));// 手动设置Id

        employeeGroup.setStatus(BusConstant.EmployeeGroup.STATUS_ENABLE);
        employeeGroup.setMakeTime(new Date());
        employeeGroup.setModifyTime(employeeGroup.getMakeTime());
        employeeGroupMapper.insert(employeeGroup);
    }

    /**
     * 修改
     * 
     * @param employeeGroup
     */
    public void update(EmployeeGroup employeeGroup) {
        String groupId = employeeGroup.getGroupId();
        if (StringUtil.isEmpty(groupId)) {
            throw new BusinessException("获取主键失败");
        }
        employeeGroup.setModifyTime(new Date());
        employeeGroupMapper.updateByPrimaryKeySelective(employeeGroup);
    }

    /**
     * 删除
     * 
     * @param groupId
     */
    public void delete(String groupId) {
        if (StringUtil.isEmpty(groupId)) {
            throw new BusinessException("获取主键失败");
        }

        EmployeeGroup employeeGroup = employeeGroupMapper.selectByPrimaryKey(groupId);
        employeeGroup.setStatus(BusConstant.EmployeeGroup.STATUS_DISABLED);
        employeeGroup.setModifyTime(new Date());
        employeeGroupMapper.updateByPrimaryKey(employeeGroup);
    }

    /**
     * 获取详情
     * 
     * @param fields
     * @param param
     * @return
     */
    @Override
    public Map<String, Object> dealFieldAlias(List<Object> fields, String param) {
        Map<String, Object> map = new HashedMap();
        for (Object field : fields) {
            map.put((String) field, new JSONArray());
        }
        SqlBuilder sqlBuilder = new SqlBuilder("SELECT a.*,e.EMP_NAME FROM EMPLOYEE_GROUP_MEMBER a "
                + "LEFT JOIN EMPLOYEE e ON e.EMP_ID = a.EMP_ID where 1=1 ").addWhereIn("a.GROUP_ID", fields)
                .orderBy("order by a.MAKE_TIME asc");
        JSONArray array = query(sqlBuilder);
        for (int i = 0; i < array.size(); i++) {
            JSONObject json = array.getJSONObject(i);
            String groupId = json.getString("groupId");
            ((JSONArray) map.get(groupId)).add(json);
        }
        return map;
    }

    /**
     * 员工部门树
     * 
     * @param reqBean
     * @return
     */
    public JSONArray empTree(ReqBean reqBean) {
        String sql = "SELECT concat('DEPT','_',d.DEPT_ID) id, d.DEPT_NAME name, concat('DEPT','_',d.PARENT_DEPT_ID) parentId " +
                "FROM SYS_DEPARTMENT d " +
                "UNION ALL " +
                "SELECT e.EMP_ID id, e.EMP_NAME name, concat('DEPT','_',e.DEPT_ID) FROM EMPLOYEE e ";
        return query(sql);
    }

    /**
     * 保存工作组成员
     * 
     * @param reqBean
     */
    public void saveMember(ReqBean reqBean) {
        String id = reqBean.getInfo("id");
        String leaderFlag = reqBean.getInfo("leaderFlag");
        String groupId = reqBean.getInfo("groupId");
        if (StringUtil.isEmpty(id) || StringUtil.isEmpty(groupId) || StringUtil.isEmpty(leaderFlag)) {
            throw new BusinessException("非法请求!");
        }

        if (leaderFlag.equals(BusConstant.LEADER_FLAG_LEADER)) {
            int count = getLeaderCount(groupId);
            if (count > 0) {
                throw new BusinessException("工作组已有组长!");
            }
        }
        EmployeeGroupMember groupMember = new EmployeeGroupMember();
        groupMember.setEmpId(id);
        groupMember.setGroupId(groupId);
        groupMember.setLeaderFlag(leaderFlag);
        groupMember.setMakeTime(new Date());
        groupMember.setModifyTime(new Date());
        groupMember.setOperator(reqBean.getUserId());
        groupMemberMapper.insert(groupMember);
    }

    /**
     * 更新组成员
     * 
     * @param reqBean
     */
    public void updateMember(ReqBean reqBean) {
        String id = reqBean.getInfo("id");
        String leaderFlag = reqBean.getInfo("leaderFlag");
        String groupId = reqBean.getInfo("groupId");
        String empId = reqBean.getInfo("empId");
        if (StringUtil.isEmpty(id) || StringUtil.isEmpty(empId) || StringUtil.isEmpty(groupId)) {
            throw new BusinessException("非法请求!");
        }

        // 是否已有组长
        if (leaderFlag.equals(BusConstant.LEADER_FLAG_LEADER)) {
            int count = getLeaderCount(groupId);
            if (count > 0) {
                throw new BusinessException("工作组已有组长!");
            }
        }
        // 先删除
        groupMemberMapper.deleteByPrimaryKey(empId, groupId);

        EmployeeGroupMember groupMember = new EmployeeGroupMember();
        groupMember.setLeaderFlag(leaderFlag);
        groupMember.setModifyTime(new Date());
        groupMember.setEmpId(id);
        groupMember.setGroupId(groupId);
        groupMember.setMakeTime(new Date());
        groupMember.setOperator(reqBean.getUserId());
        groupMemberMapper.insert(groupMember);
    }

    private int getLeaderCount(String groupId) {
        String sql = "SELECT COUNT(1) FROM EMPLOYEE_GROUP_MEMBER a where a.GROUP_ID = ? AND a.C_LEADER_FLAG = ?";
        return executeInt(sql, groupId, BusConstant.LEADER_FLAG_LEADER);
    }

    private int getMemberCount(String groupId) {
        String sql = "SELECT COUNT(1) FROM EMPLOYEE_GROUP_MEMBER a where a.GROUP_ID = ?";
        return executeInt(sql, groupId);
    }

    /**
     * 删除工作组成员
     * 
     * @param reqBean
     */
    public void deleteMember(ReqBean reqBean) {
        String empId = reqBean.getInfo("empId");
        String groupId = reqBean.getInfo("groupId");
        if (StringUtil.isEmpty(empId) || StringUtil.isEmpty(groupId)) {
            throw new BusinessException("非法请求!");
        }

        groupMemberMapper.deleteByPrimaryKey(empId, groupId);
    }

    /**
     * 工作组List
     * @param reqBean
     * @return
     */
    public JSONArray groupList(ReqBean reqBean) {
        String sql = "SELECT a.GROUP_ID,a.GROUP_NAME FROM `EMPLOYEE_GROUP` a where a.`STATUS` = ?";
        JSONArray result = query(sql, BusConstant.EmployeeGroup.STATUS_ENABLE);
        if(result !=null && !result.isEmpty()){
            for(Object o : result){
                JSONObject group = (JSONObject)o;
                group.put("members", getEmpListByGroupId(group.optString("groupId")));
            }
        }
        return result;
    }

    /**
     * 根据groupId查询所有组员
     * @param groupId
     * @return
     */
    public JSONArray getEmpListByGroupId(String groupId) {
        if(StringUtil.isEmpty(groupId)) {
            throw new BusinessException("非法请求!");
        }
        String sql = "SELECT m.*,e.EMP_NAME FROM EMPLOYEE_GROUP_MEMBER m " +
                "LEFT JOIN EMPLOYEE e ON e.EMP_ID = m.EMP_ID where m.GROUP_ID = ?";
        return query(sql,groupId);
    }
    
	/**
	 * 通过工作组id查询组员信息
	 * @param groupId
	 * @return
	 */
	public JSONArray getGroupMemberByGroupId(String groupId) {
		StringBuffer sql = new StringBuffer("select erm.*,e.EMP_NAME from EMPLOYEE_GROUP_MEMBER erm ");
		sql.append(" LEFT JOIN  EMPLOYEE_GROUP empGroup on empGroup.GROUP_ID=erm.GROUP_ID ");
		sql.append(" LEFT JOIN EMPLOYEE e on erm.EMP_ID=e.EMP_ID");
		sql.append(" where empGroup.GROUP_ID= ?");
		return query(sql.toString(), groupId);
	}
}